// Init year
document.addEventListener('DOMContentLoaded',()=>{
  const y=document.getElementById('year'); if(y) y.textContent=String(new Date().getFullYear());
  // Theme boot
  const root=document.documentElement;
  const saved=localStorage.getItem('theme');
  const prefersDark=window.matchMedia('(prefers-color-scheme: dark)').matches;
  const initial=(saved||'light');
  if(initial==='dark'){ root.setAttribute('data-theme','dark'); }
  const toggleBtn=document.getElementById('theme-toggle');
  const applyIcon=()=>{
    if(!toggleBtn) return;
    const isDark=root.getAttribute('data-theme')==='dark';
    toggleBtn.setAttribute('aria-pressed', String(isDark));
    const icon=toggleBtn.querySelector('.icon');
    if(icon) icon.textContent=isDark?'🌙':'🌞';
  };
  applyIcon();
  if(toggleBtn){
    toggleBtn.addEventListener('click',()=>{
      const isDark=root.getAttribute('data-theme')==='dark';
      if(isDark){
        root.removeAttribute('data-theme');
        localStorage.setItem('theme','light');
      }else{
        root.setAttribute('data-theme','dark');
        localStorage.setItem('theme','dark');
      }
      applyIcon();
    });
  }
});

// Smooth scroll - Lenis
let lenis;
window.addEventListener('load',()=>{
  // eslint-disable-next-line no-undef
  lenis=new Lenis({
    lerp:0.12,
    smoothWheel:true,
    syncTouch:true,
  });
  function raf(time){ lenis.raf(time); requestAnimationFrame(raf); }
  requestAnimationFrame(raf);
});

// GSAP basics
// eslint-disable-next-line no-undef
gsap.registerPlugin(ScrollTrigger);

// Particle background
async function initParticles(){
  const container=document.getElementById('particles');
  if(!container) return;
  // eslint-disable-next-line no-undef
  await tsParticles.load({ id: 'particles', options: {
    background: { color: { value: 'transparent' } },
    fpsLimit: 60,
    particles: {
      number: { value: 80, density: { enable: true, area: 800 } },
      color: { value: ['#ff3d54','#ffd2d7','#8ab6ff'] },
      shape: { type: 'circle' },
      opacity: { value: 0.3 },
      size: { value: { min: 1, max: 3 } },
      move: { enable: true, speed: 0.8, direction: 'none', outModes: 'out' },
      links: { enable: true, color: '#ff7a8a', opacity: 0.2, distance: 120, width: 1 },
    },
    detectRetina: true,
  }});
}

// Hero intro timeline
function heroIntro(){
  const tl=gsap.timeline({ defaults: { ease: 'power3.out' } });
  tl.from('.site-header', { y: -40, opacity: 0, duration: .6 })
    .from('.hero-title', { y: 30, opacity: 0, duration: .8 }, '-=.2')
    .from('.hero-sub', { y: 20, opacity: 0, duration: .6 }, '-=.4')
    .from('.hero-cta .btn', { y: 20, opacity: 0, stagger: .1, duration: .5 }, '-=.4');
}

// Reveal on scroll utility
function revealOnScroll(selector, y=40){
  gsap.utils.toArray(selector).forEach(el=>{
    gsap.from(el,{
      y,
      opacity:0,
      duration:.8,
      ease:'power3.out',
      scrollTrigger:{
        trigger: el,
        start: 'top 85%',
      }
    });
  });
}

// Card tilt effect
function cardTilt(){
  const cards=document.querySelectorAll('[data-tilt]');
  cards.forEach(card=>{
    let rect;
    function update(e){
      rect=rect||card.getBoundingClientRect();
      const px=e.clientX-rect.left; const py=e.clientY-rect.top;
      const rx=((py/rect.height)-.5)*8;
      const ry=((px/rect.width)-.5)*-8;
      card.style.transform=`perspective(800px) rotateX(${rx}deg) rotateY(${ry}deg)`;
      card.style.boxShadow=`${-ry*2}px ${rx*2}px 40px rgba(255,61,84,.18)`;
    }
    function reset(){
      card.style.transform='perspective(800px) rotateX(0) rotateY(0)';
      card.style.boxShadow='none';
      rect=undefined;
    }
    card.addEventListener('mousemove',update);
    card.addEventListener('mouseleave',reset);
  });
}

// News data with thumbnails and ids/content
const NEWS=[
  { id:'1', date:'2025-08-28', title:'「哪吒2」千人技术测试开启', desc:'招募核心玩家参与性能与战斗数值验证。', img:'images/banner1.jpg', content:'<p>技术测试将覆盖战斗系统、关卡设计与网络性能，面向核心玩家开放报名。测试期间将发放限定称号与反馈奖励。</p>' },
  { id:'2', date:'2025-07-10', title:'开发者日志 Vol.5', desc:'展示风火轮与混天绫的全新连携技。', img:'images/banner2.jpg', content:'<p>最新武器连携技引入能量共鸣机制，强化了节奏表达与视觉张力。</p>' },
  { id:'3', date:'2025-05-22', title:'获得顶级发行战略投资', desc:'加速全球上线与电竞内容生态布局。', img:'images/banner1.jpg', content:'<p>我们将加大国际化与电竞生态投入，敬请期待更多赛事计划。</p>' },
  { id:'4', date:'2025-04-02', title:'引擎渲染突破', desc:'大规模体积云与体素全局光照实装。', img:'images/banner2.jpg', content:'<p>新一代渲染管线显著提升开放世界场景表现与帧率稳定性。</p>' },
  { id:'5', date:'2025-02-12', title:'入围年度最受期待游戏', desc:'多家媒体联合评选，玩家期待值拉满。', img:'images/banner1.jpg', content:'<p>感谢玩家与媒体的认可，我们会继续打磨更好的品质。</p>' },
  { id:'6', date:'2024-12-03', title:'美术设定集预览', desc:'全平台预购赠限定数字设定集。', img:'images/banner2.jpg', content:'<p>设定集收录角色、场景与道具的高精原画与背后故事。</p>' },
];

function renderNews(){
  const list=document.getElementById('news-list');
  if(!list) return;
  list.innerHTML=NEWS.map(n=>`
    <article class="news-item">
      <div class="thumb"><img src="${n.img}" alt="${n.title}" loading="lazy"/></div>
      <div class="meta">
        <div class="news-date">${n.date}</div>
        <div class="news-title"><a href="news-detail.html?id=${n.id}">${n.title}</a></div>
        <p class="news-desc">${n.desc}</p>
      </div>
      <div class="news-more"><a href="news-detail.html?id=${n.id}">查看详情</a></div>
    </article>
  `).join('');
}

// Render news on news.html
function renderNewsListPage(){
  const list=document.getElementById('news-list-page');
  if(!list) return;
  list.innerHTML=NEWS.map(n=>`
    <article class="news-item">
      <div class="thumb"><img src="${n.img}" alt="${n.title}" loading="lazy"/></div>
      <div class="meta">
        <div class="news-date">${n.date}</div>
        <div class="news-title"><a href="news-detail.html?id=${n.id}">${n.title}</a></div>
        <p class="news-desc">${n.desc}</p>
      </div>
      <div class="news-more"><a href="news-detail.html?id=${n.id}">查看详情</a></div>
    </article>
  `).join('');
}

// Render a news detail if present
function renderNewsDetail(){
  const params=new URLSearchParams(location.search);
  const id=params.get('id');
  if(!id) return;
  const item=NEWS.find(n=>n.id===id);
  if(!item) return;
  const title=document.getElementById('news-title');
  const date=document.getElementById('news-date');
  const cover=document.getElementById('news-cover');
  const content=document.getElementById('news-content');
  if(title) title.textContent=item.title;
  if(date) date.textContent=item.date;
  if(cover) cover.innerHTML=`<img src="${item.img}" alt="${item.title}" style="width:100%;display:block"/>`;
  if(content) content.innerHTML=item.content;
}

function animateSections(){
  revealOnScroll('.section-about .about-media');
  revealOnScroll('.section-about .about-content', 30);
  revealOnScroll('.section-showcase .card', 30);
  revealOnScroll('.section-news .news-item', 24);
  revealOnScroll('.section-trailer .trailer-player', 24);
  revealOnScroll('.section-trailer .trailer-cta', 16);
  revealOnScroll('.section-guardian .gcard', 24);
  revealOnScroll('.section-guardian .guardian-content', 24);
  revealOnScroll('.section-guardian .guardian-media', 24);
  revealOnScroll('.section-contact .ctile', 20);
}

// Reduce animation on prefers-reduced-motion
const mediaQuery=window.matchMedia('(prefers-reduced-motion: reduce)');
if(mediaQuery.matches){
  // eslint-disable-next-line no-undef
  gsap.globalTimeline.timeScale(0.7);
}

window.addEventListener('load',()=>{
  initParticles();
  heroIntro();
  cardTilt();
  // renderNews();
  // renderNewsListPage();
  // renderNewsDetail();
  animateSections();
  // Video modal
  const openBtn=document.getElementById('watch-trailer');
  const modal=document.getElementById('video-modal');
  const modalVideo=document.getElementById('modal-video');
  const openModal=()=>{
    if(!modal) return;
    modal.classList.add('open');
    modal.setAttribute('aria-hidden','false');
    if(modalVideo) {
      let video_url = modalVideo.getAttribute('src');
      if (!video_url) {
        video_url = modalVideo.getAttribute('data-src');
        modalVideo.setAttribute('src', video_url);
      }
      modalVideo.currentTime=0; 
      modalVideo.play().catch(()=>{}); 
    }
    document.body.style.overflow='hidden';
  };
  const closeModal=()=>{
    if(!modal) return;
    modal.classList.remove('open');
    modal.setAttribute('aria-hidden','true');
    if(modalVideo){ modalVideo.pause(); }
    document.body.style.overflow='';
  };
  if(openBtn){ 
    openBtn.addEventListener('click', e=> { 
      e.preventDefault();
      openModal(); 
    }); 
  }
  if(modal){
    // Delegate clicks: backdrop or [data-close-modal]
    modal.addEventListener('click',e=>{
      const target=e.target;
      if(!(target instanceof Element)) return;
      if(target.matches('[data-close-modal]') || target.classList.contains('modal-backdrop')){
        closeModal();
      }
    });
  }
  window.addEventListener('keydown',e=>{ if(e.key==='Escape') closeModal(); });
  // Count-up stats when visible
  const stats=document.querySelectorAll('.about-stats .num');
  if(stats.length){
    const run=(el)=>{
      const target=Number(el.getAttribute('data-target')||0);
      const dur=1.2;
      const obj={v:0};
      gsap.to(obj,{ v:target, duration:dur, ease:'power2.out', onUpdate:()=>{
        el.textContent=Math.round(obj.v).toString();
      }});
    };
    ScrollTrigger.batch(stats,{
      start:'top 85%',
      once:true,
      onEnter:batch=>batch.forEach(run)
    });
  }
  // Reveal for contact tiles
  revealOnScroll('.section-contact .ctile', 20);
  // Lightweight parallax for elements with data-parallax
  const parallaxEls=document.querySelectorAll('[data-parallax]');
  if(parallaxEls.length){
    const update=()=>{
      parallaxEls.forEach(el=>{
        const s=parseFloat(el.getAttribute('data-parallax')||'0.15');
        const rect=el.getBoundingClientRect();
        const center=rect.top+rect.height/2-window.innerHeight/2;
        el.style.transform=`translateY(${center * -s}px)`;
      });
    };
    window.addEventListener('scroll',update,{ passive:true });
    update();
  }

  // Mobile hamburger menu for index header
  const menuBtn=document.getElementById('menu-toggle');
  const mobileMenu=document.getElementById('mobile-menu');
  if(menuBtn && mobileMenu){
    menuBtn.addEventListener('click',()=>{
      mobileMenu.classList.toggle('open');
    });
    // Close menu when clicking a link
    mobileMenu.addEventListener('click',e=>{
      const t=e.target;
      if(t && t.tagName==='A') mobileMenu.classList.remove('open');
    });
  }
  // Contact sidebar: activate panels on hash change
  function activateContactFromHash(){
    const hash=location.hash.replace('#','');
    if(!hash) return;
    const panels=document.querySelectorAll('.contact-content .c-panel');
    const links=document.querySelectorAll('.side-nav a');
    panels.forEach(p=>p.classList.remove('active'));
    links.forEach(l=>l.classList.remove('active'));
    const active=document.getElementById(hash);
    const activeLink=document.querySelector(`.side-nav a[href="#${hash}"]`);
    if(active) active.classList.add('active');
    if(activeLink) activeLink.classList.add('active');
  }
  activateContactFromHash();
  window.addEventListener('hashchange',activateContactFromHash);

  // Mobile contact select to switch panels
  const contactSelect=document.getElementById('contact-nav-select');
  if(contactSelect){
    contactSelect.addEventListener('change',()=>{
      const val=contactSelect.value;
      if(val){ location.hash = `#${val}`; }
    });
    // Sync select with current hash
    const syncSelect=()=>{
      const current=(location.hash||'#anti').replace('#','');
      contactSelect.value=current;
    };
    syncSelect();
    window.addEventListener('hashchange',syncSelect);
  }
});


